package com.cws4cloud.cws.mall.xsm.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cws4cloud.cws.common.core.util.HttpClientUtil;
import com.cws4cloud.cws.mall.xsm.config.EncryptProperties;
import com.cws4cloud.cws.mall.xsm.criteria.CgtCoCriteria;
import com.cws4cloud.cws.mall.xsm.service.XsmService;
import com.cws4cloud.cws.mall.xsm.util.OrgEncode;
import com.cws4cloud.cws.mall.xsm.util.XmlHelper;
import com.cws4cloud.cws.mall.xsm.vo.CgtCoVo;
import com.cws4cloud.cws.mall.xsm.vo.CustVo;
import com.cws4cloud.cws.mall.xsm.vo.LoginInfoVo;
import com.xsm.pub.rsa.OrgRsaEncryptDecrpyt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: XsmServiceImpl
 * @Description: 新商盟的接口实现
 * @Date 2021/6/20 17:47
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class XsmServiceImpl implements XsmService {

	@Value("${xsm.url}")
	private String rootUrl;
	@Value("${xsm.url.forverify}")
	private String forverify;
	@Value("${xsm.url.doverify}")
	private String doverify;
	@Value("${xsm.url.getCust}")
	private String getCust;
	@Value("${xsm.url.getCgtCo}")
	private String getCgtCo;
	@Value("${xsm.url.requestForPay}")
	private String requestForPay;
	@Value("${xsm.url.handlePayResult}")
	private String handlePayResult;
	@Value(("${xsm.securitykey:963741852}"))
	private String securitykey;

	private final EncryptProperties encryptProperties;
	@Override
	public String verifyCode(String securityID) {
		Map<String,Object> params = new HashMap<>();
		params.put("securityID", OrgEncode.incode(securityID));
		try {
			//调用验证码接口
			HttpClientUtil.HttpResult httpResult = HttpClientUtil.httpPostRequest(rootUrl+forverify, params);
			String response = httpResult.getResult();
			Document doc = XmlHelper.parseXmlStr(response);
			String code = doc.getDocumentElement().getAttribute("code");
			if ("0000".equals(code)) {
				String challenge = doc.getElementsByTagName("challenge")
						.item(0).getTextContent();
				return challenge;
			} else {
				String msg = doc.getDocumentElement().getAttribute("msg");
				log.error("获取验证码失败：{}", msg);
				throw new RuntimeException("获取验证码失败："+msg);
			}
		} catch (UnsupportedEncodingException e) {
			log.error("获取验证码失败：{}", e);
			throw new RuntimeException("获取验证码失败："+e.getMessage());
		}
	}

	@Override
	public LoginInfoVo login(String securityID, String username, String password, String valcode) {
		Map<String,Object> params = new HashMap<>();
		LoginInfoVo loginInfo = new LoginInfoVo();
		try {
			//调用登录接口
//			String decryptPwd = EncryptDecrypt.decrypt(URLDecoder.decode(password, "UTF-8"),securitykey);
			params.put("securityID", OrgEncode.incode(securityID));
			params.put("j_username", username);
			params.put("j_password", OrgEncode.incode(password));
			params.put("j_valcode", OrgEncode.incode(valcode));
			HttpClientUtil.HttpResult httpResult = HttpClientUtil.httpPostRequest(rootUrl+doverify, params);
			String response = httpResult.getResult();
			Document doc = XmlHelper.parseXmlStr(response);
			String code = doc.getDocumentElement().getAttribute("code");
			loginInfo.setCode(code);
			String msg = doc.getDocumentElement().getAttribute(
					"msg");
			loginInfo.setMsg(msg);
			if ("0000".equals(code)) {
				String transTime = doc.getDocumentElement().getAttribute(
						"trans_time");
				loginInfo.setTransTime(transTime);
				String userId = doc.getElementsByTagName("userId").item(0)
						.getTextContent();
				loginInfo.setUserId(userId);
				String nickName = doc.getElementsByTagName("nickName").item(0)
						.getTextContent();
				loginInfo.setNickName(nickName);
				String userType = doc.getElementsByTagName("userType").item(0)
						.getTextContent();
				loginInfo.setUserType(userType);
				String comId = doc.getElementsByTagName("comId").item(0)
						.getTextContent();
				loginInfo.setComId(comId);
				String saledptId = doc.getElementsByTagName("saledptId")
						.item(0).getTextContent();
				loginInfo.setSaledptId(saledptId);
				String refId = doc.getElementsByTagName("refId").item(0)
						.getTextContent();
				loginInfo.setRefId(refId);
				String comName = doc.getElementsByTagName("comName").item(0)
						.getTextContent();
				loginInfo.setComName(comName);
				String domainUrl = doc.getElementsByTagName("domainUrl")
						.item(0).getTextContent();
				loginInfo.setDomainUrl(domainUrl);
				String comType = doc.getElementsByTagName("comType").item(0)
						.getTextContent();
				loginInfo.setComType(comType);
				String comShort = doc.getElementsByTagName("comShort").item(0)
						.getTextContent();
				loginInfo.setComShort(comShort);
				String parentComId = doc.getElementsByTagName("parentComId")
						.item(0).getTextContent();
				loginInfo.setParentComId(parentComId);
				String expirationTime = doc
						.getElementsByTagName("expirationTime").item(0)
						.getTextContent();
				loginInfo.setExpirationTime(expirationTime);
				String planText = doc.getElementsByTagName("planText").item(0)
						.getTextContent();
				loginInfo.setPlanText(planText);
			} else {
				log.error("登录失败：{}", msg);
				throw new RuntimeException("登录失败："+msg);
			}
		} catch (UnsupportedEncodingException e) {
			log.error("登录失败：{}", e);
			throw new RuntimeException("登录失败："+e.getMessage());
		}
		return loginInfo;
	}

	@Override
	public List<CustVo> getCustVo(String securityID, String cipherText, String orgCode, String custCode) {
		Map<String,Object> params = new HashMap<>();
		try {
			if (StrUtil.isEmpty(securityID)){
				securityID = encryptProperties.getSid(orgCode);
			}
			//获取客户信息
			params.put("securityID", OrgEncode.incode(securityID));
			String publickey = encryptProperties.getPublickey(orgCode);
			params.put("cipherText", getCipherText(securityID, orgCode, custCode, publickey));
			Map<String,Object> inJsonMap = new HashMap<>();
			inJsonMap.put("ORG_CODE", OrgEncode.incode(orgCode));
			inJsonMap.put("CUST_CODE", OrgEncode.incode(custCode));
			params.put("inJson", JSONUtil.toJsonStr(inJsonMap));
			HttpClientUtil.HttpResult httpResult = HttpClientUtil.httpPostRequest(rootUrl + getCust, params);
			String outJson = httpResult.getResult();
			JSONObject jsonObject = JSONObject.parseObject(outJson);
			if ("0000".equals(jsonObject.getString("code"))) {
				List<CustVo> custVoList = JSONArray.parseArray(jsonObject.getString("DATASET"), CustVo.class);
				return custVoList;
			} else {
				String msg = jsonObject.getString("msg");
				log.error("获取客户信息失败：{}",msg);
				throw new RuntimeException("获取客户信息失败："+msg);
			}

		}catch (UnsupportedEncodingException e) {
			log.error("获取客户信息失败：{}",e);
			throw new RuntimeException("获取客户信息失败："+e.getMessage());
		}
	}

	@Override
	public List<CgtCoVo> getCgtCoVo(CgtCoCriteria cgtCoCriteria) {
		Map<String,Object> params = new HashMap<>();
		try {
			String sid = cgtCoCriteria.getSecurityID();
			if (StrUtil.isEmpty(sid)){
				sid = encryptProperties.getSid(cgtCoCriteria.getOrgCode());
			}
			//获取客户信息
			params.put("securityID", OrgEncode.incode(sid));
			String publickey = encryptProperties.getPublickey(cgtCoCriteria.getOrgCode());
			params.put("cipherText", getCipherText(sid, cgtCoCriteria.getOrgCode(), cgtCoCriteria.getCustCode(), publickey));
			Map<String,Object> inJsonMap = new HashMap<>();
			inJsonMap.put("ORG_CODE", OrgEncode.incode(cgtCoCriteria.getOrgCode()));
			inJsonMap.put("CUST_CODE", OrgEncode.incode(cgtCoCriteria.getCustCode()));
			inJsonMap.put("CO_NUM", OrgEncode.incode(cgtCoCriteria.getCoNum()));
			inJsonMap.put("ORDER_DATE", OrgEncode.incode(cgtCoCriteria.getOrderDate()));
			inJsonMap.put("BDATE", OrgEncode.incode(cgtCoCriteria.getBeginDate()));
			inJsonMap.put("EDATE", OrgEncode.incode(cgtCoCriteria.getEndDate()));
			params.put("inJson", JSONUtil.toJsonStr(inJsonMap));
			HttpClientUtil.HttpResult httpResult = HttpClientUtil.httpPostRequest(rootUrl + getCgtCo, params);
			String outJson = httpResult.getResult();
			JSONObject jsonObject = JSONObject.parseObject(outJson);
			if ("0000".equals(jsonObject.getString("code"))) {
				List<CgtCoVo> custVoList = JSONArray.parseArray(jsonObject.getString("DATASET"), CgtCoVo.class);
				return custVoList;
			} else {
				String msg = jsonObject.getString("msg");
				log.error("获取客户信息失败：{}",msg);
				throw new RuntimeException("获取客户信息失败："+msg);
			}

		}catch (UnsupportedEncodingException e) {
			log.error("获取客户信息失败：{}",e);
			throw new RuntimeException("获取客户信息失败："+e.getMessage());
		}
	}

	private static String getCipherText(String sid, String orgCode,
								 String custCode,String publickey) {
		String arg = sid + "," + orgCode + "," + custCode + ","
				+ System.currentTimeMillis();
		OrgRsaEncryptDecrpyt.initOrgWithKey(orgCode, publickey, "");
		System.out.println(OrgRsaEncryptDecrpyt.isOrgInitialized(orgCode));
		String str = null;
		try {
			str = OrgRsaEncryptDecrpyt.orgEncrpytWithPublicKey(orgCode, arg);
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
}
